#!/bin/sh
set -e
if [ -z "$SYSROOT" ]; then export SYSROOT="$(realpath "$(dirname "$0")/../sysroot")"; fi
if [ -z "$LLVMDIR" ]; then export LLVMDIR="$(realpath "$(dirname "$0")/../llvm-project")"; fi
if [ -f "$SYSROOT/bin/musl-gcc" ]; then export CC="$SYSROOT/bin/musl-gcc"; fi
if [ -f "$SYSROOT/bin/musl-clang" ]; then export CC="$SYSROOT/bin/musl-clang"; fi

# libcxx needs futex.h in atomic.cpp for FUTEX_WAIT_PRIVATE and FUTEX_WAKE_PRIVATE
# the host linux header pulls in a ton of other headers, so let's just make one ourselves
mkdir -p "$SYSROOT/include/linux"
rm -f "$SYSROOT/include/linux/futex.h"
printf "%s\n%s\n" "#define FUTEX_WAIT_PRIVATE 128" "#define FUTEX_WAKE_PRIVATE 129" > "$SYSROOT/include/linux/futex.h"

rm -rf build1
mkdir build1
cd build1
export CFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none"
export CXXFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none -fno-use-cxa-atexit"
export LDFLAGS="-no-pie"

cmake \
	-DCMAKE_C_COMPILER="$CC" \
	-DCMAKE_CXX_COMPILER="$CC" \
	-DLIBCXX_ENABLE_SHARED=OFF \
	-DLIBCXX_CXX_ABI="system-libcxxabi" \
	-DLIBCXX_CXX_ABI_INCLUDE_PATHS="$LLVMDIR/libcxxabi/include" \
	-DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON \
	-DLIBCXX_STATICALLY_LINK_ABI_IN_STATIC_LIBRARY=OFF \
	-DLIBCXX_ENABLE_RANDOM_DEVICE=OFF \
	-DLIBCXX_ENABLE_TIME_ZONE_DATABASE=OFF \
	-DLIBCXX_HAS_MUSL_LIBC=ON \
	-DLIBCXX_USE_COMPILER_RT=ON \
	-DLIBCXX_INCLUDE_TESTS=OFF \
	-DLIBCXX_INCLUDE_BENCHMARKS=OFF \
	-DLIBCXX_INCLUDE_DOCS=OFF \
	-DCMAKE_INSTALL_PREFIX="$SYSROOT" \
	$LLVMDIR/libcxx
